package com.taobao.ued.toy.dao;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;

import java.sql.ResultSet;

public class DaoUtils {

	public static void copyBeanFromRs(Object bean, ResultSet rs, String[] fields) throws Exception {
		for (String field : fields) {
			BeanUtils.setProperty(bean, field, rs.getObject(field));
		}
	}

	public static String getUpdateParam(String[] fields) {
		StringBuffer sb = new StringBuffer();
		for (String field : fields) {
			sb.append(",").append(field).append(" = :").append(field);
		}
		return sb.substring(1);
	}

	public static MapSqlParameterSource getParamSource(Object bean, String[] fields) throws Exception {
		MapSqlParameterSource params = new MapSqlParameterSource();
		for (String field : fields) {
			params.addValue(field, BeanUtils.getProperty(bean, field));
		}
		return params;
	}

	public static String[] getFieldsForParams(String[] fields) {
		String[] ret = new String[fields.length];
		for (int i = 0; i < fields.length; i++) {
			ret[i] = ":" + fields[i];
		}
		return ret;
	}

}
